package com.stone.inventory.sharding.infra.algorithm;

import com.stone.inventory.sharding.config.properties.DbShardingProperty;
import com.stone.inventory.sharding.config.properties.GlobalIdProperties;
import com.stone.inventory.sharding.config.properties.TableRuleProperty;
import lombok.Data;

/**
 * 分片算法抽象
 *
 * @author Mr_wenpan@163.com 2021/8/16 11:22 下午
 */
@Data
public abstract class AbstractShardingAlgorithm<T> implements ShardingAlgorithm<T> {

    private Long tableMask;
    private Long tableBitShift;
    private TableRuleProperty tableRuleProperty;

    public AbstractShardingAlgorithm(DbShardingProperty dbShardingProperty) {

        GlobalIdProperties idProperties = dbShardingProperty.getShardingIdRule();
        tableBitShift = idProperties.getSequenceBits() + idProperties.getNodeBits();
        tableMask = (~(-1L << idProperties.getTableBits())) << tableBitShift;
        tableRuleProperty = dbShardingProperty.getTableRules().get(logicTableName());
    }

    @Override
    public String getTargetTableByShardingId(Long id) {

        int index = (int) (id & tableMask) >> tableBitShift;
        return tableRuleProperty.getActualTables().get(index);
    }
}